package com.arcaneshift.servlet.system;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.arcaneshift.model.request.system.GetAllGamesRequest;
import com.arcaneshift.model.response.system.GetAllGamesResponse;
import com.arcaneshift.model.validators.system.SessionValidator;
import com.arcaneshift.model.validators.user.AdminValidator;
import com.arcaneshift.servlet.util.network.RequestAction;
import com.arcaneshift.servlet.util.parser.system.GetAllGamesXMLParser;
import com.arcaneshift.util.GameCacheContainer;
import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.model.validators.ActionValidator;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.common.servlet.interfaces.IParser;

public class GetAllGamesServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;
	private static Set<AbstractValidator> validators = new HashSet<AbstractValidator>();

	private GetAllGamesRequest requestContent;
	private GetAllGamesXMLParser parser = new GetAllGamesXMLParser();
	
	static {
		validators.add(new ActionValidator(RequestAction.GET_ALL_GAMES));
		validators.add(new SessionValidator());
		validators.add(new AdminValidator());
	}
	
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) {
		try {
			GetAllGamesResponse allGamesResponse = new GetAllGamesResponse();
			
			allGamesResponse.setRequestAction(requestContent.getAction());
			allGamesResponse.setGames(GameCacheContainer.getAll());
			
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseResponse(allGamesResponse));
			response.getWriter().close();
		} catch (ParserException parserException) {
			exception(parserException, response);
		} catch (IOException e) {
			error(new ParserError(ParserError.STREAM_ERROR), response);
		}
	}

	@Override
	public void setRequest(AbstractRequest abstractRequest) {
		requestContent = (GetAllGamesRequest) abstractRequest;
	}

	@Override
	public Set<AbstractValidator> getValidators() {
		return validators;
	}

	@Override
	public IParser parser() {
		return parser;
	}
}
